<?php
/**
 * Slipstream :: Highly adaptive dependency injection framework
 * Copyright 2010-2011 Ian Unruh (Xerof3ar)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Slipstream\Configuration\Option;

use InvalidArgumentException;
use Terrafirma\Predicate\PredicateInterface;

/**
 * Option that uses a predicate to perform validation on its set value
 *
 * @author Ian Unruh (Xerof3ar) <ianunruh@gmail.com>
 * @since Class avaliable since release 1.0
 */
class PredicatedOption extends AbstractOption
{
	/**
	 * @var PredicateInterface
	 */
	protected $predicate;
	
	/**
	 * Class constructor
	 *
	 * @param string $name
	 * @param PredicateInterface $predicate [optional]
	 * @param mixed $value [optional]
	 * @return void
	 */
	public function __construct($name, PredicateInterface $predicate = null, $value = null)
	{
		parent::__construct($name, $value);
		$this->predicate = $predicate;
	}
	
	/**
	 * Returns the predicate for this option
	 * @return PredicateInterface
	 */
	public function getPredicate()
	{
		return $this->predicate;
	}
	
	/**
	 * Sets the predicate for this option
	 *
	 * @param PredicateInterface $predicate
	 * @return void
	 */
	public function setPredicate(PredicateInterface $predicate)
	{
		$this->predicate = $predicate;
	}
	
	/**
	 * Validates the set value of this option
	 *
	 * @throws Exception If set value is not valid
	 * @return void
	 */
	public function validate()
	{
		if(!$this->predicate->evaluate($this->value)) {
			throw new InvalidArgumentException(sprintf('Invalid value set for option "%s"', $this->name));
		}
	}
}